package com.huatek.framework.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.huatek.framework.entity.FwAccount;
import com.huatek.framework.exception.BusinessRuntimeException;
import com.huatek.framework.security.ClientInfoBean;
import com.huatek.framework.security.ClientInformationImpl;
import com.huatek.framework.security.IValidateUser;
import com.huatek.framework.security.ThreadLocalClient;

public class LoginFilter implements Filter {
	private static final String ERROR_MESSAGE = "errorMessage";
	private static final String ERROR_LABLE = "errorLable";
	private static final String VALIDATE_USER_SERVICE = "validateUserService";
	private static final Logger logger = Logger.getLogger(LoginFilter.class);

	private String userNameField = "userName";

	private String passwordField = "password";

	private String formNameField = "loginForm";

	private String welcomeAction = "/welcome.do";

	//private ServletContext servletContext;

	//private static WebApplicationContext webContext = null;

	public void destroy() {
		ThreadLocalClient.remove();
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hRequest = (HttpServletRequest) request;
		if (hRequest.getSession().getAttribute(
				ClientInformationImpl.LOGIN_ACCOUNT) == null
				|| request.getParameter(formNameField) != null) {
			if (request.getParameter(formNameField) == null) {
				request.setAttribute(ERROR_LABLE,
						"errors.login.session.timeout");
			} else {

				try {
					IValidateUser validateUserService = (IValidateUser) SpringContext
							.getBean(VALIDATE_USER_SERVICE);
					FwAccount user = (FwAccount) validateUserService.getUser(
							request.getParameter(userNameField), request
									.getParameter(passwordField));
					hRequest.getSession().setAttribute(
							ClientInformationImpl.LOGIN_ACCOUNT, user);
				} catch (BusinessRuntimeException e) {
					if (logger.isDebugEnabled()) {
						logger.debug(e.getMessage());
					}
					request.setAttribute(ERROR_LABLE, e.getErrorKey());
				} catch (Exception e) {
					if (logger.isDebugEnabled()) {
						logger.debug(e.getMessage());
					}
					request.setAttribute(ERROR_MESSAGE, e.getMessage());
				}
			}
		}
		if (hRequest.getAttribute(ERROR_MESSAGE) != null
				|| hRequest.getAttribute(ERROR_LABLE) != null) {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher(welcomeAction);
			dispatcher.forward(request, response);
		} else {
			if (ThreadLocalClient.get() != null) {
				ClientInfoBean cientInfo = (ClientInfoBean)ThreadLocalClient.get();
				cientInfo.setOperator((FwAccount)hRequest.getSession().getAttribute(
						ClientInformationImpl.LOGIN_ACCOUNT));
			}
			// pass the request along the filter chain
			chain.doFilter(request, response);
		}

	}

	public void init(FilterConfig fConfig) throws ServletException {

		if (fConfig.getInitParameter("formNameField") != null) {
			formNameField = fConfig.getInitParameter("formNameField");
		}
		if (fConfig.getInitParameter("userNameField") != null) {
			userNameField = fConfig.getInitParameter("userNameField");
		}
		if (fConfig.getInitParameter("passwordField") != null) {
			passwordField = fConfig.getInitParameter("passwordField");
		}
		if (fConfig.getInitParameter("welcomeAction") != null) {
			welcomeAction = fConfig.getInitParameter("welcomeAction");
		}

	}

}
